package com.maixy.nettyserverdemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @ClassName HelloServer
 * @Description TODO
 * @Date 2021/4/7 20:46
 * @Author maixy
 */
public class HelloServer {
    public static void main(String[] args) {
        //启动器，负责组装netty组件，启动服务器
        new ServerBootstrap()
                //NioEventLoopGroup包含BossEventLoop和WorkerEventLoop(selector,thread),group 组
                .group(new NioEventLoopGroup())
                //选择服务器ServerSocketChannel实现
                .channel(NioServerSocketChannel.class)
                //boss 负责处理连接 worker（child）负责读写，决定work（child）能执行那些操作（handler）
                .childHandler(
                        //channel代表和客户端进行数据读写的通道，Initializer 初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //添加具体handler
                        nioSocketChannel.pipeline().addLast(new StringDecoder());//将ByteBuf转换为字符串
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){//自定义handler
                            @Override//读事件
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                //打印上一步转换好的字符串
                                System.out.println(msg);
                            }
                        });
                    }
                }).bind(10003);
    }
}
